<template>
  <div>
    <el-form class="userForm" :inline="true">
      <el-button class="addUser" @click="addUser" type="primary" size="small"><i class="el-icon-edit-outline"></i>添加用户</el-button>
      <el-form-item label="用户名：">
        <el-input placeholder="请输入需要查询用户名" v-model="username" size="small"></el-input>
      </el-form-item>
      <el-button class="button0" @click="inquery" type="primary" size="small"><i class="el-icon-search"></i>查询</el-button>
      <el-button class="button0" @click="clearFilter" size="small"><i class="el-icon-refresh"></i>重置</el-button>
    </el-form>

    <el-table ref="filterTable" border :data="userData" style="width:95%">
      <el-table-column type="index" width="80px"></el-table-column>
      <el-table-column prop="username" label="姓名" width="200px"></el-table-column>
      <el-table-column
        prop="gender.name"
        label="性别"
        width="200px"
        :filters="[{ text: '男', value: '男' }, { text: '女', value: '女' }]"
        :filter-method="filterTag"
        filter-placement="bottom-end"
      >
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.gender.name === '男' ? 'success' : 'danger'"
            disable-transitions
          >{{scope.row.gender.name}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="250px"></el-table-column>
      <el-table-column
        prop="role.name"
        label="角色"
        width="200"
        column-key="role.name"
        :filters="[{text:'管理员',value:'管理员'},{text:'仓库管理员',value:'仓库管理员'},{text:'客服',value:'客服'},{text:'商品管理员',value:'商品管理员'}]"
        :filter-method="filterHandler"
      ></el-table-column>
      <el-table-column prop="createDate" label="创建时间" width="250" column-key="createDate" sortable :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="操作" width="210" fixed="right">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="deleteUser(scope.$index, userData,scope.row)"
            type="text"
            size="small"
          >删除</el-button>
          <el-button @click.native.prevent="updateUser(scope.row)" type="text" size="small">修改</el-button>
        </template>
      </el-table-column>
    </el-table>


    <el-dialog
      :visible.sync="userDialogVisible"
      :title="userDialogTitle"
      width="450px"
      :before-close="handleClose"
    >
      <el-form :model="userForm" :rules="rules" ref="userForm">
        <el-form-item label="用户名：" prop="username" label-width="100px">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password" label-width="100px">
          <el-input v-model="userForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="性别：" label-width="100px" prop="gender.code">
          <el-radio-group v-model="userForm.gender">
            <el-radio v-for="item in genders" :label="item.code" :key="item.code">{{item.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号：" label-width="100px" prop="phone">
          <el-input v-model="userForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="角色：" label-width="100px" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option v-for="item in roles" :key="item.code" :label="item.name" :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="button" @click="clearUser">重置</el-button>
          <el-button class="button" @click="submit('userForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  addUser,
  deleteUser,
  updateUser,
  getUserById,
  getUserByUsername,
  getUserAll,
} from "@/api/user.js";
import { getGenders, getRoles } from "@/api/common.js";
export default {
  data() {
    return {
      userData: [],
      username: "",
      userDialogVisible: false,
      userDialogTitle: "添加用户",
      userForm: {
        username: "",
        password: "",
        gender: { code: "", name: "" },
        phone: "",
        role: { code: "", name: "" },
      },
      roles:[],
      genders: [],
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 4,
            max: 10,
            message: "长度在 4 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 4,
            max: 20,
            message: "长度在 4 到 20 个字符",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          {
            min: 10,
            max: 11,
            message: "请输入正确的电话号码",
            trigger: "blur",
          },
        ],
        role: [{ required: true, message: "请选择角色", trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.show();
  },
  methods: {
    show() {
      console.log("----")
      getUserAll().then((res) => {
        console.log(res);
        if (res.data.code === "0000") {
          this.userData = res.data.data;
        }
      });
      this.showGenders();
      this.showRoles();
    },
    showGenders() {
      getGenders().then((res) => {
        // console.log(res);
        if (res.data.code === "0000") {
          this.genders = res.data.data;
        }
      });
    },
    showRoles() {
      getRoles().then((res) => {
        // console.log(res);
        if (res.data.code === "0000") {
          this.roles = res.data.data;
        }
        
      });
    },
    clearFilter() {
      this.$refs.filterTable.clearFilter();
      this.show()
    },
    filterTag(value, row) {
      return row.gender.name === value;
    },
    filterHandler(value, row) {
      return row.role.name === value;
    },
    deleteUser(index, userData, row) {
      if (confirm("真的要删除该用户吗？")) {
        deleteUser(row.id).then((res) => {
          if (res.data.code === "0000") {
            userData.splice(index, 1);
          }
        });
      }
    },
    updateUser(row) {
      this.userDialogVisible = true;
      this.userDialogTitle = "修改用户";
      getUserById(row.id).then(res=>{
        console.log(res)
        if (res.data.code === "0000") {
          this.userForm = res.data.data;
          this.userForm.gender=this.userForm.gender.code
          this.userForm.role=this.userForm.role.name
        }
      })
    },
    addUser() {
      this.userForm={}
      this.userDialogVisible = true;
      this.userDialogTitle = "添加用户";
    },
    clearUser() {
      this.userForm = {};
    },
    submit(formName) {
      console.log(this.userForm);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.userDialogTitle === "添加用户") {
            addUser(this.userForm).then((res) => {
              if (res.data.code === "0000") {
                this.$message.success("添加成功");
              }
            });
          } else {
            updateUser(this.userForm).then((res) => {
              if (res.data.code === "0000") {
                this.$message.success("修改成功");
              }
            });
          }
          this.userDialogVisible = false;
          setTimeout(()=>{this.show()},1000) 
        } else {
          return false;
        }
      });
    },
    handleClose() {
      this.userDialogVisible = false;
    },
    inquery() {
      getUserByUsername(this.username).then((res) => {
        if (res.data.code === "0000") {
               this.userData=res.data.data
               this.username=""
              }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.userForm {
  margin-top: 20px;
}
.addUser {
  margin-right: 100px;
}
// .el-table{
//    margin-top: 20px;
// }
.button {
  margin-left: 80px;
}
.button0 {
  margin-left: 20px;
}
.el-input {
  width: 220px;
}
.el-form-item {
  margin-left: 20px;
}
</style>